//运行参数：--experimental-worker
const {
    // isMainThread,
    // parentPort,
    // workerData,
    // threadId,
    // MessageChannel,
    // MessagePort,
    Worker
} = require('worker_threads');

function runWorker(path, workerData, msgCb, errorCb, exitCb) {
    let worker = new Worker(path, { workerData });
    worker.on('message', data=>{
        // console.log("main recv: "+data);
        if (msgCb) {
            msgCb(data);
        }
    });
    worker.on('error', err=>{
        if (errorCb) {
            errorCb(err);
        }
    }); 
    worker.on('exit', (exitCode) => {
        if (exitCb) {
            exitCb(exitCode);
        }
    });
    worker.close = function() {
        this.postMessage({cmd:"close"});
    }
    return worker;
}

function runWorkerOnce(path, workerData, errorCb, exitCb) {
    let worker = new Worker(path, { workerData });
    worker.on('error', err=>{
        if (errorCb) {
            errorCb(err);
        }
    }); 
    worker.on('exit', (exitCode) => {
        if (exitCb) {
            exitCb(exitCode);
        }
    });
    return worker;
}

module.exports.runWorker = runWorker;
module.exports.runWorkerOnce = runWorkerOnce;

// let work = runWorker("./thread_work.js", 1, data=>{
//     console.log("main recv: "+data);
// });
// work.postMessage(10);
// work.close();